<script lang="ts" setup>
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElUpload,
  ElIcon,
  ElMessage,
  ElTreeSelect,
} from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { getUserSimpleInfo, edit } from "#/api/sys/user";
import { getOrganizationsByUserId } from "#/api/sys/organization";
import mapCenter from "./mapCenter.vue";
import Upload from "#/adapter/component/Upload/Upload.vue";
import { useDebounceFn } from "@vueuse/core";
const disabled = ref(false);
const acceptImg = ref(".jpg,.jpeg,.png");
const isShowTip = reactive({
  isShow: true,
  message: "支持JPG/PNG格式，大小不超过5MB",
});

const ruleFormRef = ref();
const ruleForm = reactive<RuleForm>({
  id: "",
  userName: "",
  realName: "",
  organizationName: "",
  organizationId: "",
  logoUrl: "",
  mobile: "",
  mapCenterName: "",
  longitude: "", // 经度
  latitude: "", // 纬度
});

const spaceInput = (field: string, value: string) => {
  // 过滤空格
  ruleForm[field] = value.replace(/\s+/g, "");
};

const updateImg = (img) => {
  ruleForm.logoUrl = img;
};

const treeData = ref([]);
const defaultProps = {
  children: "children",
  label: "organizationName",
};
const rules = reactive({
  realName: [{ min: 1, max: 20, message: "请输入最多20字", trigger: "blur" }],
  userName: [{ min: 1, max: 20, message: "请输入最多20字", trigger: "blur" }],
  mobile: [
    {
      pattern: /^1[3456789]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

const isOrganizationName = ref(false);
const isRealName = ref(false);
const isUserName = ref(false);
const isMobile = ref(false);

const updateItem = (val) => {
  switch (val) {
    case "organizationName":
      isOrganizationName.value = true;
      break;
    case "userName":
      isUserName.value = true;
      break;
    case "realName":
      isRealName.value = true;
      break;
    case "mobile":
      isMobile.value = true;
      break;
  }
};

// 如果有默认LOGO
onMounted(() => {
  // if (!ruleForm.logoUrl) {
  //   ruleForm.logoUrl = '/default-logo.png';
  // }
});

// 地图配置
const mapConfig = reactive({
  defaultAddress: "天安门",
  defaultPoint: [116.397428, 39.90923] as [number, number],
});

const getPosition = (infoObj) => {
  if (infoObj.defaultAddress) {
    ruleForm.mapCenterName = infoObj.defaultAddress;
    ruleForm.longitude = infoObj.defaultPoint[0];
    ruleForm.latitude = infoObj.defaultPoint[1];
  }
};

const getTableData = async () => {
  const { data } = await getOrganizationsByUserId();
  treeData.value = data;
};

const submitForm = async () => {
  const params = {
    id: ruleForm.id,
    organizationId: ruleForm.organizationId,
    userName: ruleForm.userName,
    realName: ruleForm.realName,
    mobile: ruleForm.mobile,
    imageUrl: ruleForm.logoUrl,
    mapCenterName: ruleForm.mapCenterName,
    longitude: ruleForm.longitude,
    latitude: ruleForm.latitude,
  };
  const { data } = await edit(params);
  ElMessage.success("修改成功!");
  getInfo();
};

const debouncedSubmitForm = useDebounceFn(submitForm, 500);

const getInfo = async () => {
  const { data } = await getUserSimpleInfo();
  ruleForm.id = data.id;
  ruleForm.logoUrl = data.imageUrl;
  ruleForm.organizationId = data.organizationId;
  ruleForm.organizationName = data.organizationName;
  ruleForm.userName = data.userName;
  ruleForm.realName = data.realName;
  ruleForm.mobile = data.mobile;
  ruleForm.mapCenterName = data.mapCenterName;
  ruleForm.longitude = data.longitude;
  ruleForm.latitude = data.latitude;
  // 更新地图配置
  mapConfig.defaultAddress = data.mapCenterName;
  mapConfig.defaultPoint = [ruleForm.longitude, ruleForm.latitude];
};

onMounted(() => {
  getTableData();
  getInfo();
});
</script>

<template>
  <div class="p-2">
    <div class="page">
      <ElForm
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <ElFormItem label="系统LOGO：" prop="logoUrl">
          <Upload
            v-model:imgUrl="ruleForm.logoUrl"
            :isShowTip="isShowTip"
            :disabled="disabled"
            :accept="acceptImg"
            @updateImg="updateImg"
          />
        </ElFormItem>
        <ElFormItem label="组织名称：" prop="organizationName">
          <div v-if="isOrganizationName == false" class="flex">
            <span>{{ ruleForm.organizationName }}</span>
            <ElButton
              link
              @click="updateItem('organizationName')"
              class="update"
              >修改</ElButton
            >
          </div>
          <ElTreeSelect
            v-if="isOrganizationName == true"
            v-model="ruleForm.organizationId"
            :data="treeData"
            :props="defaultProps"
            node-key="id"
            :render-after-expand="false"
            check-strictly
            placeholder="请选择所属组织"
            style="width: 300px"
          />
        </ElFormItem>
        <ElFormItem label="登录账号：" prop="userName">
          <div v-if="isUserName == false" class="flex">
            <span>{{ ruleForm.userName }}</span>
            <ElButton link @click="updateItem('userName')" class="update"
              >修改</ElButton
            >
          </div>
          <ElInput
            v-if="isUserName == true"
            v-model="ruleForm.userName"
            @input="(value) => spaceInput('userName', value)"
            placeholder="请输入"
            style="width: 300px"
          />
        </ElFormItem>
        <ElFormItem label="姓名：" prop="realName">
          <div v-if="isRealName == false" class="flex">
            <span>{{ ruleForm.realName }}</span>
            <ElButton link @click="updateItem('realName')" class="update"
              >修改</ElButton
            >
          </div>
          <ElInput
            v-if="isRealName == true"
            v-model="ruleForm.realName"
            @input="(value) => spaceInput('realName', value)"
            placeholder="请输入"
            style="width: 300px"
          />
        </ElFormItem>
        <ElFormItem label="手机号码：" prop="mobile">
          <div v-if="isMobile == false" class="flex">
            <span>{{ ruleForm.mobile }}</span>
            <ElButton link @click="updateItem('mobile')" class="update"
              >修改</ElButton
            >
          </div>
          <ElInput
            v-if="isMobile == true"
            v-model="ruleForm.mobile"
            @input="(value) => spaceInput('mobile', value)"
            placeholder="请输入"
            style="width: 300px"
          />
        </ElFormItem>
        <ElFormItem label="地图中心点：" prop="mapCenterName">
          <div class="flex">
            <p>
              {{ ruleForm.mapCenterName }}（{{ ruleForm.longitude }},{{
                ruleForm.latitude
              }}）
            </p>
            <!-- <ElButton
              link
              @click="updateItem('mapCenterName')"
              class="update"
              >修改</ElButton
            > -->
          </div>
          <mapCenter :data="mapConfig" @getPosition="getPosition" />
        </ElFormItem>
        <ElFormItem>
          <div style="width: 100%; text-align: center">
            <el-button type="primary" @click="debouncedSubmitForm">
              保存
            </el-button>
          </div>
        </ElFormItem>
      </ElForm>
    </div>
  </div>
</template>
<style scoped>
.page {
  font-size: 14px;
}

.update {
  margin-left: 10px;
  color: var(--el-color-primary);
}

.logo-uploader {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.logo-preview {
  position: relative;
  width: 148px;
  height: 148px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.logo-actions {
  position: absolute;
  right: 0;
  bottom: 0;
  padding: 4px;
  background: rgb(0 0 0 / 50%);
  border-radius: 4px 0 0;
}

.el-upload__tip {
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.update {
  margin-left: 8px;
}

:deep(.el-form-item__label) {
  color: #909399 !important;
}
</style>
